#ifndef EXPORTPROGRESSMANAGER_H
#define EXPORTPROGRESSMANAGER_H

#include <QObject>
#include <QString>
#include <QTimer>
#include <QMap>

// 前向声明
class MergedExportManager;
class UnifiedPageRenderer;
class StatusBarManager;

// 需要的包含
#include "unifiedfileinfo.h"  // 包含LayoutMode枚举定义

enum class ExportStage {
    Initializing = 1,    // 初始化准备 (0-5%)
    FileAnalysis = 2,    // 文件分析 (5-10%)
    LayoutProcessing = 3, // 布局处理 (10-60%) - 最耗时
    RenderingPrep = 4,   // 渲染准备 (60-75%)
    PDFGeneration = 5,   // PDF生成 (75-95%)
    Finalizing = 6       // 完成保存 (95-100%)
};

struct FileData {
    QString path;
    QString name;
    int pageCount;
    int layoutMode;
    bool enhancementEnabled;

    FileData() : pageCount(0), layoutMode(1), enhancementEnabled(false) {}
    FileData(const QString& p, const QString& n, int pc, int lm, bool enh = false)
        : path(p), name(n), pageCount(pc), layoutMode(lm), enhancementEnabled(enh) {}
};

struct ProgressInfo {
    int percentage;
    QString message;
    QString currentFile;
    QString estimatedTime;
    ExportStage stage;
};

class ExportProgressManager : public QObject
{
    Q_OBJECT

public:
    explicit ExportProgressManager(QObject* parent = nullptr);
    ~ExportProgressManager();

    // 导出控制
    void startExport(const QList<FileData>& files);
    void cancelExport();
    void pauseExport();
    void resumeExport();

    // 设置实际导出组件
    void setExportComponents(MergedExportManager* exporter, UnifiedPageRenderer* renderer);

    // 进度更新
    void updateProgress(int percentage, const QString& message);
    void setCurrentStage(ExportStage stage);

    // 状态查询
    bool isExporting() const { return m_isExporting; }
    bool isPaused() const { return m_isPaused; }
    bool isCancelled() const { return m_isCancelled; }
    ExportStage currentStage() const { return m_currentStage; }
    int currentProgress() const { return m_currentProgress; }

public slots:
    // 各阶段的入口
    void startFileAnalysisStage();
    void startLayoutProcessingStage();
    void startRenderingPrepStage();
    void startPDFGenerationStage();
    void startFinalizingStage();

signals:
    void progressUpdated(const ProgressInfo& progress);
    void stageChanged(ExportStage stage, const QString& stageName);
    void exportCompleted(const QString& outputPath);
    void exportCancelled();
    void exportFailed(const QString& error);

    // 内部信号
    void layoutProcessingCompleted();

private slots:
    void onLayoutProcessingFinished();
    void onAnalysisTimer();
    void onRenderingPrepTimer();
    void onFinalizingTimer();

    // 实际导出的槽函数
    void onActualExportCompleted(const QString& outputPath);
    void onActualExportFailed(const QString& error);
    void onActualExportProgress(int percentage);

private:
    // 阶段管理
    void setupStageNames();
    void setProgressRange(int min, int max);
    void emitProgressUpdate(const QString& message, const QString& currentFile = QString());

    // 异步处理
    void executeLayoutProcessing();
    void executeFileAnalysis();

    // 时间估算
    struct TimeEstimate {
        qint64 estimatedMs;
        QString formattedTime;
        QString confidence;
    };

    TimeEstimate estimateTotalTime(const QList<FileData>& files) const;
    qint64 estimateFileTime(const FileData& file) const;
    QString formatTime(qint64 ms) const;
    QString getConfidenceLevel(int fileCount) const;

    // 辅助方法
    QString generateOutputPath();

    // 取消检查
    bool checkCancellation() const;

    // 成员变量
    QList<FileData> m_files;
    ExportStage m_currentStage;
    int m_currentProgress;
    QString m_currentMessage;
    bool m_isExporting;
    bool m_isPaused;
    bool m_isCancelled;

    QMap<ExportStage, QString> m_stageNames;
    QMap<ExportStage, QPair<int, int>> m_stageRanges;

    QTimer* m_analysisTimer;
    QTimer* m_renderingPrepTimer;
    QTimer* m_finalizingTimer;

    QString m_outputPath;

    // 布局处理进度状态
    int m_layoutFileIndex;
    int m_layoutPageIndex;
    int m_layoutTotalOperations;
    int m_layoutCompletedOperations;

    // 进度估算器
    class ProgressEstimator* m_estimator;

    // 实际导出组件
    MergedExportManager* m_actualExporter;
    UnifiedPageRenderer* m_pageRenderer;
};

// 进度估算器类
class ProgressEstimator {
public:
    struct TimeEstimate {
        qint64 estimatedMs;
        QString formattedTime;
        QString confidence;
    };

    TimeEstimate estimateTotalTime(const QList<FileData>& files) const {
        qint64 totalMs = 0;

        for (const auto& file : files) {
            totalMs += estimateFileTime(file);
        }

        return {
            totalMs,
            formatTime(totalMs),
            getConfidenceLevel(files.size())
        };
    }

    TimeEstimate getRemainingTime(int currentPercentage) const {
        if (currentPercentage <= 0) return {0, "未知", "低"};

        qint64 elapsed = m_elapsedTimer.elapsed();
        qint64 estimated = (elapsed * 100) / currentPercentage;
        qint64 remaining = estimated - elapsed;

        return {
            remaining,
            formatTime(remaining),
            currentPercentage > 50 ? "较高" : "中等"
        };
    }

    void startTimer() {
        m_elapsedTimer.start();
    }

private:
    qint64 estimateFileTime(const FileData& file) const {
        qint64 baseTime = 500; // 基础时间500ms
        qint64 pageTime = file.pageCount * 50; // 每页50ms

        qint64 layoutMultiplier = 1;
        if (file.layoutMode == 2) layoutMultiplier = 3; // 双栏3倍时间
        if (file.layoutMode == 3) layoutMultiplier = 5; // 三栏5倍时间

        qint64 enhancementTime = file.enhancementEnabled ? 200 : 0;

        return (baseTime + pageTime + enhancementTime) * layoutMultiplier;
    }

    QString formatTime(qint64 ms) const {
        if (ms < 1000) return QString("< 1秒");
        if (ms < 60000) return QString("%1秒").arg(ms / 1000);
        return QString("%1分%2秒").arg(ms / 60000).arg((ms % 60000) / 1000);
    }

    QString getConfidenceLevel(int fileCount) const {
        if (fileCount < 3) return "较高";
        if (fileCount < 10) return "中等";
        return "一般";
    }

    mutable QElapsedTimer m_elapsedTimer;
};

#endif // EXPORTPROGRESSMANAGER_H